package com.egrand.sweetapi.plugin.db.provider;

import com.egrand.sweetapi.starter.db.DynamicRoutingDataSource;
import com.egrand.sweetapi.starter.db.provider.AbstractJdbcDataSourceProvider;
import com.egrand.sweetapi.starter.db.provider.DynamicDataSourceProvider;
import com.egrand.sweetapi.starter.db.spring.boot.autoconfigure.DataSourceProperty;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class EgdTenantDataSourceProvider extends AbstractJdbcDataSourceProvider
        implements DynamicDataSourceProvider {

    public EgdTenantDataSourceProvider(String url, String username, String password) {
        super(url, username, password);
    }

    @Override
    protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
        ResultSet st = statement.executeQuery("select t.code, t.url, t.username, t.password from egd_tenant_datasource t where t.status = 0");
        Map<String, DataSourceProperty> maps = new HashMap<>();
        while(st.next()){
            DataSourceProperty dataSourceProperty = new DataSourceProperty();
            dataSourceProperty.setPoolName(st.getString("code"));
            dataSourceProperty.setUrl(st.getString("url"));
            dataSourceProperty.setUsername(st.getString("username"));
            dataSourceProperty.setPassword(st.getString("password"));
            maps.put(st.getString("code"), dataSourceProperty);
        }
        return maps;
    }

    public void execute(DataSource dataSource){
        log.info("init load tenant datasources");
        DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
        Map<String, DataSource> dataSourceMap = this.loadDataSources();
        for (Map.Entry<String, DataSource> dsItem : dataSourceMap.entrySet()) {
            ds.addDataSource(dsItem.getKey(), dsItem.getValue());
        }
    }
}
